<?php

namespace app\store\model\presalesCustomer;

class Type extends \app\common\model\presalesCustomer\Type
{
    /**
     * 检索查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认查询条件
        $param = $this->setQueryDefaultValue($param, [
            'search' => '',
            'status' => -1,
            'create_time' => [],
        ]);
        // 检索查询条件
        $filter = [];
        !empty($param['search']) && $filter[] = ['type_name|type_desc', 'like', "%{$param['search']}%"];
        $param['status'] > -1 && $filter[] = ['status', '=', $param['status']];

        if (!empty($param['create_time'])) {
            $times = between_time($param['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    /**
     * 获取列表记录
     * @param array $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = [], array $store = []): \think\Paginator
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 查询列表数据
        return $this->where($filter)
            ->where('is_delete', '=', 0)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }

    public function all(array $param = [], array $store = [])
    {
        // 检索查询条件
        $filter = $this->getFilter($param);

        // 查询列表数据
        return $this->where($filter)
            ->where('is_delete', '=', 0)
            ->where('status', '=', 0)
            ->order(['create_time' => 'desc'])
            ->select();
    }

    public function findCustomerTypeId($name)
    {
        $info = $this->where(['type_name' => $name, 'status' => 0, 'is_delete' => 0])->find();
        if (!$info) {
            return 0;
        }
        return $info->pct_id;
    }

    /**
     * 添加新记录
     * @param array $data
     * @return bool|false
     */
    public function adds(array $data, array $store = []): bool
    {
        if (!empty($data['is_default'])) {
            if ($this->getDefaultType()) {
                $this->error = '添加失败：已存在默认类型，请勿重复添加！';
                return false;
            }
        }

        $data['store_id'] = self::$storeId;
        return $this->save($data) !== false;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edits(array $data): bool
    {
        if (!empty($data['is_default']) && $this->is_default != $data['is_default']) {
            if ($this->getDefaultType()) {
                $this->error = '操作失败：已存在默认类型！';
                return false;
            }
        }
        return $this->save($data) !== false;
    }

    /**
     * 获取当前默认类型
     */
    public function getDefaultType()
    {
        return $this->where(['is_default' => 1, 'is_delete' => 0])->find();
    }
}
